import { Ref, onUnmounted, ref, watch } from "vue";

/**
 *
 * @param NodeRef 监听的节点 ref
 * @param loadMore 加载下一页的函数
 * @returns { hasMore,setHasMore }
 */
const useIntersectionObserver = (
  NodeRef: Ref<HTMLElement | null>,
  loadMore: () => void
) => {
  // 是否有下一页
  const hasMore = ref(true);
  // 用于监听节点
  let observer: IntersectionObserver = new IntersectionObserver(([entry]) => {
    if (entry.isIntersecting) {
      // 该节点出现在视图中时触发回调，加载更多
      loadMore();
    }
  });
  // 监听节点变化
  watch(NodeRef, (newNodeRef, oldNodeRef) => {
    console.log("节点变化，");
    console.log("hasMore", hasMore.value);
    // 取消监听旧节点
    if (oldNodeRef) {
      observer.unobserve(oldNodeRef);
    }
    // 开始监听新节点
    if (newNodeRef) {
      observer.observe(newNodeRef);
    }
  });
  // 监听hasMore变化，在没有下一页时，取消监听
  watch(hasMore, (value) => {
    console.log("hasMore", hasMore.value);

    if (!value) observer.disconnect();
  });
  // 组件卸载，取消监听
  onUnmounted(() => {
    observer.disconnect();
  });

  return {
    hasMore,
    setHasMore: (value: boolean) => {
      hasMore.value = value;
    },
  };
};

export default useIntersectionObserver;
